#include "DashboardUI_AddPrescription.h"
#include "ui_dashboard_addprescription.h"

#include "Authentication.h"
#include "PrescriptionDatabase.h"

#include "InfoBoxUI.h"

DashboardUI_AddPrescription::DashboardUI_AddPrescription(QWidget *parent) :
    QWidget(parent),
    validator(this),
    ui(new Ui::DashboardUI_AddPrescription)
{
    ui->setupUi(this);

    ui->prescribedDateField->setDate(QDate::currentDate());
    ui->completionDateField->setDate(QDate::currentDate());

    validator.addAllFields();
    validator.setButton(ui->submitButton);
}

DashboardUI_AddPrescription::~DashboardUI_AddPrescription()
{
    delete ui;
}

void DashboardUI_AddPrescription::clearFields()
{
    validator.resetFields();

    ui->commentField->clear();

    ui->prescribedDateField->setDate(QDate::currentDate());
    ui->completionDateField->setDate(QDate::currentDate());
}

void DashboardUI_AddPrescription::on_submitButton_clicked()
{
    Authentication * auth = Authentication::getInstance();

    PersonDatabase personDB;
    PersonInfo info = personDB.getInfo(auth->getUser()->getId());

    QString prescriber = info.firstName + " " + info.lastName;

    Prescription p;
    p.prescriptionName = ui->prescriptionNameField->text();
    p.refills = ui->refillsField->text().toInt();
    p.prescribeDate = ui->prescribedDateField->date();
    p.completeDate = ui->completionDateField->date();
    p.comments = ui->commentField->toPlainText();
    p.prescribedBy = prescriber;

    User * patient = auth->getPatient();
    if (patient == nullptr)
        return;

    PrescriptionDatabase prescripDB;
    prescripDB.addPrescription(&p, patient->getId());

    new InfoBoxUI("Prescription added", 2000, this);

    clearFields();
}
